<?php
/**
 * Created by PhpStorm.
 * User: xiaomeng
 * Date: 17-9-18
 * Time: 下午3:41
 */
namespace swf\common;

class Curl
{
    private $curl = null;

    public function __construct()
    {
        $this->curl = curl_init();
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($this->curl, CURLOPT_HEADER, 0);
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);

    }

    private function init($url)
    {
        curl_setopt($this->curl, CURLOPT_URL, $url);
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
    }
    public function post($url,$data)
    {
        $this->init($url);
        curl_setopt($this->curl,CURLOPT_POST,1);
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, array('Expect:'));
        curl_setopt($this->curl,CURLOPT_POSTFIELDS,$data);
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Cache-Control: no-cache',
                'Content-Length: ' . strlen($data)
            )
        );
        $res = $this->exec();
        return $res;

    }

    public function get($url)
    {
        $this->init($url);
        curl_setopt($this->curl, CURLOPT_HEADER, 0);
        curl_setopt($this->curl, CURLOPT_TIMEOUT,10);
        $res = $this->exec();
        return $res;
    }


    private function exec()
    {
        $data = curl_exec($this->curl);
        if($data === false)
        {
            $this->error = curl_errno($this->curl);
            $this->errorMsg = curl_error($this->curl);
        }
        return $data;

    }

    public function __destruct()
    {
        curl_close($this->curl);
    }
}